package me.firstapp.repository.weixin.transfer.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import me.firstapp.module.weixin.transfer.TransferMember;
import me.firstapp.repository.base.impl.EntityRepositoryImpl;
import me.firstapp.repository.weixin.transfer.TransferMemberRepository;

@Repository
public class TransferMemberRepositoryImpl extends EntityRepositoryImpl<TransferMember>
		implements TransferMemberRepository {

	@Override
	protected Class<TransferMember> getPersistentClass() {
		return TransferMember.class;
	}

	@Override
	public Long findMemberTransferCounts(Long ownMemberId) {
		StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM TransferMember bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		sql.append(" AND bean.ownMemberId = :ownMemberId ");
		parameters.put("ownMemberId", ownMemberId);

		sql.append(" AND bean.status = :status ");
		parameters.put("status", TransferMember.STATUS_NORMAL);

		List<Long> result = super.query(Long.class, sql.toString(), parameters);
		return result.isEmpty() ? 0L : result.get(0);
	}

	@Override
	public List<TransferMember> findTransferMembers(Long ownMemberId, Integer status) {
		StringBuilder sql = new StringBuilder(" FROM TransferMember bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		sql.append(" AND bean.ownMemberId = :ownMemberId ");
		parameters.put("ownMemberId", ownMemberId);

		if (null != status) {
			sql.append(" AND bean.status = :status ");
			parameters.put("status", status);
		}

		return super.query(TransferMember.class, sql.toString(), parameters);
	}

	@Override
	public TransferMember findTransferMember(Long memberId, Long ownMemberId) {
		StringBuilder sql = new StringBuilder(" FROM TransferMember bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		sql.append(" AND bean.ownMemberId = :ownMemberId ");
		parameters.put("ownMemberId", ownMemberId);

		sql.append(" AND bean.memberId = :memberId ");
		parameters.put("memberId", memberId);

		List<TransferMember> result = super.query(TransferMember.class, sql.toString(), parameters);

		return result.isEmpty() ? null : result.get(0);
	}

}
